package com.twu.biblioteca.users;

import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;

import java.util.HashSet;
import java.util.Set;


/**
 * @author Alvi Jonathan Sait
 */
public class UserAccountsManager {

    private final Set<User> registeredUsers;
    private Optional<User> currentlyActiveUser;

    public UserAccountsManager() {
        this.registeredUsers = new HashSet<User>();
        this.currentlyActiveUser = Optional.absent();
    }

    public Optional<User> getCurrentlyActiveUser() {
        return currentlyActiveUser;
    }

    public void registerUser(User user) {
        registeredUsers.add(user);
    }

    /**
     * Verifies if the given username and password pair is available in the list of registered users.
     */
    public Optional<User> authenticateUser(final String username, final String password) {
        Optional<User> possibleUser = Iterables.tryFind(registeredUsers, new Predicate<User>() {
            @Override
            public boolean apply(User user) {
                return user.getUsername().equals(username) &&
                        user.getPassword().equals(password);
            }
        });
        this.currentlyActiveUser = possibleUser;
        return possibleUser;
    }

}
